<script setup>
import PageHeader from "@/components/PageHeader/index.vue";
import {approveAbsBack, approveApply0, listAdminAbsence, listStudentAbsence} from "@/api/absence/index.js";
import {onMounted, ref} from "vue";
import {absClassDict, absClassFormat, absStatusDict, absStatusFormat} from "@/utils/common_absence.js";
import {convertISOToBasicString} from "@/utils/common1.js";
import {approveCompetitionApply} from "@/api/competition/index.js";
import {ElMessage} from "element-plus";

//查询条件
const queryParams = ref({
  current: 1,
  size: 20,
  data: {
    status: null,
    uid: null,
    userName: null,
    stuClass: null,
    startTime: null,
    endTime: null,
  }
})

//查询条件控制
const queryParamsControl = ref({
  table: {
    total: 0,
    loading: false,
    data: []
  },
  status: {
    option: [],
    loading: false
  }
})

let DateRange = ref([]) // 申请时间范围查询条件

const handleDateRange = (value) => {
  console.log(value[0])
  queryParams.value.data.startTime = convertISOToBasicString(value[0])
  queryParams.value.data.endTime = convertISOToBasicString(value[1])
}

const getList = async () => {
  const data = await listAdminAbsence(queryParams.value)
  console.log(data)

  queryParamsControl.value.table.data = data.data
  queryParamsControl.value.table.total = data.count
  queryParamsControl.value.table.loading = false
}

// 查询
function handleQuery() {
  queryParams.value.current = 1
  getList()
}

// 重置
function handleReset() {
  queryParams.value = {
    current: 1,
    size: 20,
    data: {
      status: null,
      uid: null,
      userName: null,
      stuClass: null,
      startTime: null,
      endTime: null,
    }
  }
  DateRange.value = []
  getList()
}

const tableRef = ref() //表格ref
const multipleSelection = ref([]); // 已选择的row

const selectable = (row) => ![1, 2].includes(row.id);

const handleSelectionChange = (val) => {
  multipleSelection.value = val;
  console.log("val", val);
};

const statusDict = ref([]) // 审核状态option
const classDict = ref([]) // 年级option

let imgDrawer = ref(false) //抽屉开关
let rowCache = ref() //存一下抽屉对应row
let urlList = ref([]) //预览图片用

//打开抽屉img
const handleOpenImgDraw = (row) => {
  urlList.value = [] //先清空原先的
  rowCache.value = row
  urlList.value.push(row.url)
  imgDrawer.value = true
}

onMounted(() => {
  getList()
  statusDict.value = absStatusDict()
  classDict.value = absClassDict()
})

const approveStatus0 = async (value) => {
  let applyIdCache = []
  console.log("multipleSelection.value:",multipleSelection.value)
  multipleSelection.value.forEach(item => {
    if(item.status === 0) //只有处于0（待审核）才能用
      applyIdCache.push(item.id)
  })

  const res = await approveApply0(value,applyIdCache)
  console.log(applyIdCache)
  if(res.msg) {
    ElMessage.error(res.msg)
  } else {
    ElMessage.success("已处理")
    handleReset()
    multipleSelection.value = []
  }
}

//批假(单一
const approveStatus0_1= async (bool, row) => {
  const applicationIds = [row.id]
  const res = await approveApply0(bool, applicationIds)
  if(res.msg) {
    ElMessage.error(res.msg)
  } else {
    ElMessage.success("已处理")
    handleReset()
    multipleSelection.value = []
  }
}

//审批销假(单一
const approveBack = async (bool, row) => {
  const applicationIds = [row.id]
  const res = await approveAbsBack(bool, applicationIds)
  if(res.msg) {
    ElMessage.error(res.msg)
  } else {
    ElMessage.success("已处理")
    handleReset()
    multipleSelection.value = []
  }
}

//审批销假(批量
const approveBack_n = async (bool) => {
  let applyIdCache = []
  console.log("multipleSelection.value:",multipleSelection.value)
  multipleSelection.value.forEach(item => {
    if(item.status === 3) //只有处于3（已申请销假）才能用
      applyIdCache.push(item.id)
  })
  const res = await approveAbsBack(bool, applyIdCache)
  if(res.msg) {
    ElMessage.error(res.msg)
  } else {
    ElMessage.success("已处理")
    handleReset()
    multipleSelection.value = []
  }
}

</script>

<template>
  <div class="app-container">
    <el-card class="box">
      <PageHeader>
        <el-form :model="queryParams" inline>
          <el-form-item label="学号">
            <el-input
                v-model="queryParams.data.uid"
                placeholder="请输入学生学号"
                clearable
            />
          </el-form-item>
          <el-form-item label="姓名">
            <el-input
                v-model="queryParams.data.userName"
                placeholder="请输入学生姓名"
                clearable
            />
          </el-form-item>
          <el-form-item label="学生年级">
            <el-select
                v-model="queryParams.data.stuClass"
                placeholder="请选择年级"
                style="width: 200px"
                clearable
                filterable
                :loading="queryParamsControl.status.loading"
            >
              <el-option
                  v-for="item in classDict"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="审核状态">
            <el-select
                v-model="queryParams.data.status"
                placeholder="请选择审核状态"
                style="width: 200px"
                clearable
                filterable
                :loading="queryParamsControl.status.loading"
            >
              <el-option
                  v-for="item in statusDict"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="申请时间范围">
            <el-date-picker
                v-model="DateRange"
                type="daterange"
                range-separator="To"
                start-placeholder="起始日期"
                end-placeholder="结束日期"
                @change="handleDateRange"
            />
          </el-form-item>
        </el-form>
        <template #left>
          <el-popover placement="right"
                      :width="180"
                      trigger="click">
            <template #reference>
              <el-button type="primary">
                <el-icon><EditPen /></el-icon>批量审核
              </el-button>
            </template>
            <span style="padding-top: 8px;font-weight: bold">审批为： </span>
            <el-button type="success" @click="approveStatus0(true)"  link>同意</el-button>
            <el-button type="danger" @click="approveStatus0(false)"  link>拒绝</el-button>
          </el-popover>
          <el-popover placement="right"
                      :width="180"
                      trigger="click">
            <template #reference>
              <el-button type="warning">
                <el-icon><EditPen /></el-icon>批量销假
              </el-button>
            </template>
            <span style="padding-top: 8px;font-weight: bold">审批为： </span>
            <el-button type="success" @click="approveBack_n(true)"  link>已核实返校</el-button>
            <el-button type="danger" @click="approveBack_n(false)"  link>夜不归宿</el-button>
          </el-popover>
        </template>
        <template #right>
          <ElButton class="queryBtn" type="primary" @click="handleQuery">查询</ElButton>
          <ElButton class="resetBtn" plain @click="handleReset">重置</ElButton>
        </template>
      </PageHeader>
    </el-card>
    <el-card class="box">
      <el-table
          height="400"
          ref="tableRef"
          v-loading="queryParamsControl.table.loading"
          :data="queryParamsControl.table.data"
          row-key="id"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="expand">
          <template #default="props">
            <div class="table_description">
              <el-descriptions :column="2" class="cell_description" border>
                <el-descriptions-item label="监护人电话">{{props.row.number}}</el-descriptions-item>
                <el-descriptions-item label="请假证明">
                  <el-button type="primary" link @click="handleOpenImgDraw(props.row)">查看图片
                  </el-button>
                </el-descriptions-item>
                <el-descriptions-item label="请假原因">{{props.row.reason}}</el-descriptions-item>
                <el-descriptions-item label="离校时间">{{props.row.leavingTime}}</el-descriptions-item>
                <el-descriptions-item label="离校期间所在地">{{props.row.position}}</el-descriptions-item>
                <el-descriptions-item label="预计返校时间">{{props.row.backingTime}}</el-descriptions-item>
                <el-descriptions-item v-if="[1,2,3,4,5].includes(props.row.status)" label="批假时间">{{props.row.approvalTime}}</el-descriptions-item>
                <el-descriptions-item v-if="[3,4,5].includes(props.row.status)" label="申请销假时间">{{props.row.checkingTime}}</el-descriptions-item>
                <el-descriptions-item v-if="[4,5].includes(props.row.status)" label="销假时间">{{props.row.approvedTime}}</el-descriptions-item>
              </el-descriptions>
            </div>
          </template>
        </el-table-column>
        <el-table-column type="selection" :selectable="selectable" fixed="left" width="50" />
        <el-table-column type="index" fixed="left" width="54" label="序号" />
        <el-table-column label="学号" prop="uid" show-overflow-tooltip />
        <el-table-column label="请假学生" prop="userName" show-overflow-tooltip />
        <el-table-column label="班级" prop="stuClass" show-overflow-tooltip />
        <el-table-column label="请假状态" prop="status" :formatter="absStatusFormat()" show-overflow-tooltip />
        <el-table-column label="请假原因" prop="reason" show-overflow-tooltip />
        <el-table-column label="申请时间" prop="applicationTime" show-overflow-tooltip />
        <ElTableColumn label="操作" width="124" fixed="right">
          <template #default="{row}">
            <el-popover placement="left"
                        :width="180"
                        trigger="click"
                        v-if="[3].includes(row.status)">
              <template #reference>
                <el-button
                    plain
                    type="warning"
                    link
                >销假确认</el-button>
              </template>
              <div style="padding-top: 8px;font-weight: bold">审批为： </div>
              <el-button type="success" @click="approveBack(true,row)"  link>已核实返校</el-button>
              <el-button type="danger" @click="approveBack(false,row)"  link>夜不归宿</el-button>
            </el-popover>
            <el-popover placement="left"
                        :width="180"
                        trigger="click"
                        v-if="[0].includes(row.status)">
              <template #reference>
                <el-button
                    plain
                    type="success"
                    link
                >审核</el-button>
              </template>
              <div style="padding-top: 8px;font-weight: bold">审批为： </div>
              <el-button type="success" @click="approveStatus0_1(true,row)"  link>同意</el-button>
              <el-button type="danger" @click="approveStatus0_1(false,row)"  link>拒绝</el-button>
            </el-popover>
          </template>
        </ElTableColumn>
      </el-table>

      <el-pagination
          @size-change="getList"
          @current-change="getList"
          v-model:current-page="queryParams.current"
          v-model:page-size="queryParams.size"
          :page-sizes="[5, 10, 20, 50]"
          :background="true"
          layout="prev, pager, next, jumper,->,sizes,total"
          :total="queryParamsControl.table.total"
          style="margin-top: 8px"
      />

    </el-card>

    <el-drawer
        v-model="imgDrawer"
        title="图片证明"
        direction="ltr"
    >
      <div class="imgBox">
        <el-image :src="rowCache.url"
                  :fit="'fill'"
                  :preview-src-list="urlList"
        ></el-image>
      </div>

    </el-drawer>

  </div>
</template>

<style scoped lang="scss">
.box {
  margin-bottom: 8px;
}

.table_description {
  padding-left: 150px;
}

.imgBox {
  width: 300px;
  height: 300px
}

</style>